package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;
	@Resource
	private RedisTemplate redisTemplate;

	@Resource
	WxMaService wxMaService;
    @Autowired
    private RabbitService rabbitService;
	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;

	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;

	/**
	 * 根据用户Id、专辑ID，获取已经支付的声音ID列表
	 * @param albumId
	 * @param userId
	 * @return
	 */
	@Override
	public List<Long> findUserPaidTrackList(Long albumId, Long userId) {
		//select track_id from user_paid_track where user_id=17 and album_id=391;
		return userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userId).eq(UserPaidTrack::getAlbumId, albumId)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
	}

	/**
	 * 判断用户是否购买了专辑
	 *
	 * @param albumId
	 * @param userId
	 * @return
	 */
	@Override
	public Boolean isPaidAlbum(Long albumId, Long userId) {
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getId, albumId));
		if(null!=userPaidAlbum){
			return true;
		}
		return false;
	}

	/**
	 *  判断用户是否购买了声音
	 * @param albumId 专辑Id
	 * @param trackIdList 付费声音Id 列表; 6-25;
	 * @param userId 用户Id
	 * @return
	 */
	@Override
	public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> trackIdList, Long userId) {
		//	创建map 集合
		Map<Long, Integer> map = new HashMap<>();
		//判断用户是否购买了专辑,user_paid_album
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getId, albumId));
		if (null!=userPaidAlbum) {
			//	这个用户购买过专辑 map.put(trackId,1); map.put(trackId,0); 1:表示已经购买; 0:表示未购买 setIsShowPaidMark(true);
			return trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
		}
		//未购买专辑，判断用户是否购买声音，已购买，设1
		List<Long> userPaidTrackList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>()
				.eq(UserPaidTrack::getUserId, userId)
				.eq(UserPaidTrack::getAlbumId, albumId)
				.in(UserPaidTrack::getTrackId, trackIdList)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
		//	查询到的结果是：这个用户购买过哪些声音 userPaidTrackList 这个集合可能为空：说明用户未购买过任何一条声音;

		for (Long trackId : trackIdList) {
			if(userPaidTrackList.contains(trackId)){
				//已买过，1
				map.put(trackId,1);
			}else{
				//未买过，0
				map.put(trackId,0);
			}
		}
		//	返回集合;
		return map;
	}

	/**
	 * 修改用户信息
	 * @param userInfoVo
	 * @param userId
	 */
	@Override
	public void updateUser(UserInfoVo userInfoVo, Long userId) {
		UserInfo userInfo = new UserInfo();
		//属性拷贝
		BeanUtils.copyProperties(userInfoVo,userInfo);
		userInfo.setId(userId);
		//更新用户信息
		userInfoMapper.updateById(userInfo);
	}

	/**
	 * 根据用户ID，获取用户信息
	 * @param userId
	 * @return
	 */
	@Override
	public UserInfoVo getUserInfo(Long userId) {
		//获取用户信息
		UserInfo userInfo = userInfoMapper.selectById(userId);

		//属性拷贝
		UserInfoVo userInfoVo = new UserInfoVo();
		BeanUtils.copyProperties(userInfo,userInfoVo);
		return userInfoVo;
	}

	/**
	 * 微信登录
	 * @param code
	 * @return
	 */
	@Override
	public Map<String, Object> wxLogin(String code) {
		HashMap<String, Object> map = new HashMap<>();

		WxMaJscode2SessionResult wxMaJscode2SessionResult=null;
		try {
			//1、根据临时登录凭证，获取wxMaJscode2SessionResult（openid,appId,secretKey）
            wxMaJscode2SessionResult= wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
		//2、获取微信用户的唯一标识openId
		String openid = wxMaJscode2SessionResult.getOpenid();
		//3、根据openId,查询用户信息，有说明，已注册；没有，注册并初始化Account
		UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
		if(null==userInfo){
			//4、创建用户
			userInfo = new UserInfo();
			userInfo.setWxOpenId(openid);
			userInfo.setNickname("用户" + UUID.randomUUID().toString().replaceAll("-", ""));
			userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
			//	添加到表中;
			userInfoMapper.insert(userInfo);
			//5、rabbitMq给UseAccount微服务发消息,初始化账户
			//common>>rabbit-util>>RabbitService
			rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
		}
		//6、缓存UserInfo，放入redis中，
		String token= UUID.randomUUID().toString().replace("-","");
		redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

		//7、返回token，给前端
		map.put("token",token);
		return map;
	}
}
